<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">测试数据生成</h1>
      <p class="page-subtitle">基于现有数据源和表结构生成测试数据</p>
    </div>
    
    <div class="page-content">
      <!-- 步骤指示器 -->
      <el-steps :active="currentStep" finish-status="success" class="steps-container">
        <el-step title="选择数据源" />
        <el-step title="选择表" />
        <el-step title="配置字段" />
        <el-step title="生成数据" />
      </el-steps>

      <!-- 步骤1: 选择数据源 -->
      <el-card shadow="hover" class="step-card" v-show="currentStep === 0">
        <template #header>
          <div class="card-header">
            <span>步骤1: 选择数据源</span>
          </div>
        </template>
        
        <div class="datasource-selection">
          <el-row :gutter="20">
            <el-col 
              :span="8" 
              v-for="datasource in datasourceOptions" 
              :key="datasource.id"
              class="datasource-item"
            >
              <el-card 
                :class="['datasource-card', { 'selected': selectedDatasource?.id === datasource.id }]"
                @click="selectDatasource(datasource)"
                shadow="hover"
              >
                <div class="datasource-info">
                  <div class="datasource-icon">🗄️</div>
                  <div class="datasource-details">
                    <div class="datasource-name">{{ datasource.name }}</div>
                    <div class="datasource-type">{{ datasource.type.toUpperCase() }}</div>
                    <div class="datasource-host">{{ datasource.host }}:{{ datasource.port }}</div>
                    <div class="datasource-status">
                      <el-tag :type="datasource.status === 'connected' ? 'success' : 'danger'" size="small">
                        {{ datasource.status === 'connected' ? '已连接' : '未连接' }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
          
          <div class="step-actions">
            <el-button type="primary" @click="nextStep" :disabled="!selectedDatasource">
              下一步
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 步骤2: 选择表 -->
      <el-card shadow="hover" class="step-card" v-show="currentStep === 1">
        <template #header>
          <div class="card-header">
            <span>步骤2: 选择表</span>
            <el-button type="text" @click="prevStep">返回上一步</el-button>
          </div>
        </template>
        
        <div class="table-selection">
          <div class="selected-datasource-info">
            <el-alert 
              :title="`已选择数据源: ${selectedDatasource?.name}`" 
              type="info" 
              :closable="false"
              show-icon
            />
          </div>
          
          <div class="table-search">
            <el-input
              v-model="tableSearchKeyword"
              placeholder="搜索表名"
              style="width: 300px"
              clearable
            >
              <template #prefix>
                🔍
              </template>
            </el-input>
            <el-button type="primary" @click="loadTables" :loading="loadingTables">
              刷新表列表
            </el-button>
          </div>
          
          <div class="table-list">
            <el-row :gutter="20">
              <el-col 
                :span="6" 
                v-for="table in filteredTables" 
                :key="table"
                class="table-item"
              >
                <el-card 
                  :class="['table-card', { 'selected': selectedTable === table }]"
                  @click="selectTable(table)"
                  shadow="hover"
                >
                  <div class="table-info">
                    <div class="table-icon">📋</div>
                    <div class="table-name">{{ table }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
          
          <div class="step-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button type="primary" @click="nextStep" :disabled="!selectedTable">
              下一步
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 步骤3: 配置字段 -->
      <el-card shadow="hover" class="step-card" v-show="currentStep === 2">
        <template #header>
          <div class="card-header">
            <span>步骤3: 配置字段</span>
            <el-button type="text" @click="prevStep">返回上一步</el-button>
          </div>
        </template>
        
        <div class="field-configuration" v-loading="loadingSchema">
          <div class="selected-info">
            <el-alert 
              :title="`数据源: ${selectedDatasource?.name} | 表: ${selectedTable}`" 
              type="info" 
              :closable="false"
              show-icon
            />
          </div>
          
          <el-form :model="form" label-width="120px" class="config-form">
            <el-form-item label="生成记录数">
              <el-input-number 
                v-model="form.record_count" 
                :min="1" 
                :max="100000" 
                style="width: 200px"
              />
              <span class="form-tip">建议不超过10000条</span>
            </el-form-item>
            
            <el-form-item label="清空现有数据">
              <el-switch v-model="form.truncate_table" />
              <span class="form-tip">开启后会先清空表中的现有数据</span>
            </el-form-item>
          </el-form>
          
          <div class="fields-config">
            <div class="fields-header">
              <h3>字段配置</h3>
              <div class="header-actions">
                <el-button type="primary" @click="autoConfigAllFields">智能配置</el-button>
                <el-button @click="toggleAllFields">全选/取消</el-button>
              </div>
            </div>
            
            <div class="fields-list">
              <div class="field-item" v-for="(field, index) in tableFields" :key="field.name">
                <div class="field-header">
                  <el-checkbox v-model="field.generate" @change="updateFieldGenerate(index)">
                    <span class="field-name">{{ field.name }}</span>
                    <el-tag size="small" class="field-type-tag">{{ field.db_type }}</el-tag>
                    <el-tag v-if="field.is_primary" type="warning" size="small">主键</el-tag>
                    <el-tag v-if="field.auto_increment" type="success" size="small">自增</el-tag>
                  </el-checkbox>
                </div>
                
                <div class="field-config" v-if="field.generate && !field.auto_increment">
                  <div class="config-row">
                    <label class="config-label">数据类型:</label>
                    <el-select v-model="field.type" @change="handleFieldTypeChange(index)" style="width: 150px">
                      <el-option label="自增ID" value="id" />
                      <el-option label="整数" value="integer" />
                      <el-option label="浮点数" value="float" />
                      <el-option label="字符串" value="string" />
                      <el-option label="日期时间" value="datetime" />
                      <el-option label="日期" value="date" />
                      <el-option label="布尔值" value="boolean" />
                      <el-option label="枚举" value="enum" />
                      <el-option label="姓名" value="name" />
                      <el-option label="手机号" value="phone" />
                      <el-option label="邮箱" value="email" />
                      <el-option label="地址" value="address" />
                      <el-option label="IP地址" value="ip" />
                      <el-option label="UUID" value="uuid" />
                      <el-option label="文本" value="text" />
                    </el-select>
                  </div>
                  
                  <!-- 整数类型配置 -->
                  <div class="config-row" v-if="field.type === 'integer'">
                    <label class="config-label">数值范围:</label>
                    <el-input-number v-model="field.min" placeholder="最小值" style="width: 120px" />
                    <span class="range-separator">-</span>
                    <el-input-number v-model="field.max" placeholder="最大值" style="width: 120px" />
                  </div>
                  
                  <!-- 浮点数类型配置 -->
                  <div class="config-row" v-if="field.type === 'float'">
                    <label class="config-label">数值范围:</label>
                    <el-input-number v-model="field.min" placeholder="最小值" :precision="2" style="width: 120px" />
                    <span class="range-separator">-</span>
                    <el-input-number v-model="field.max" placeholder="最大值" :precision="2" style="width: 120px" />
                    <label class="config-label" style="margin-left: 20px">精度:</label>
                    <el-input-number v-model="field.precision" :min="0" :max="10" style="width: 80px" />
                  </div>
                  
                  <!-- 字符串类型配置 -->
                  <div class="config-row" v-if="field.type === 'string' || field.type === 'text'">
                    <label class="config-label">长度范围:</label>
                    <el-input-number v-model="field.min_length" placeholder="最小长度" :min="0" style="width: 120px" />
                    <span class="range-separator">-</span>
                    <el-input-number v-model="field.max_length" placeholder="最大长度" :min="1" style="width: 120px" />
                  </div>
                  
                  <!-- 日期时间类型配置 -->
                  <div class="config-row" v-if="field.type === 'datetime'">
                    <label class="config-label">时间范围:</label>
                    <el-date-picker
                      v-model="field.start_date"
                      type="datetime"
                      placeholder="开始时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 180px"
                    />
                    <span class="range-separator">-</span>
                    <el-date-picker
                      v-model="field.end_date"
                      type="datetime"
                      placeholder="结束时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 180px"
                    />
                  </div>
                  
                  <!-- 日期类型配置 -->
                  <div class="config-row" v-if="field.type === 'date'">
                    <label class="config-label">日期范围:</label>
                    <el-date-picker
                      v-model="field.start_date"
                      type="date"
                      placeholder="开始日期"
                      value-format="YYYY-MM-DD"
                      style="width: 150px"
                    />
                    <span class="range-separator">-</span>
                    <el-date-picker
                      v-model="field.end_date"
                      type="date"
                      placeholder="结束日期"
                      value-format="YYYY-MM-DD"
                      style="width: 150px"
                    />
                  </div>
                  
                  <!-- 枚举类型配置 -->
                  <div class="config-row" v-if="field.type === 'enum'">
                    <label class="config-label">枚举值:</label>
                    <el-input 
                      v-model="field.values" 
                      placeholder="用逗号分隔，如：男,女" 
                      style="width: 300px"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="step-actions">
            <el-button @click="prevStep">上一步</el-button>
            <el-button type="primary" @click="nextStep">下一步</el-button>
          </div>
        </div>
      </el-card>

      <!-- 步骤4: 生成数据 -->
      <el-card shadow="hover" class="step-card" v-show="currentStep === 3">
        <template #header>
          <div class="card-header">
            <span>步骤4: 生成数据</span>
            <el-button type="text" @click="prevStep">返回上一步</el-button>
          </div>
        </template>
        
        <div class="data-generation">
          <div class="generation-summary">
            <el-descriptions title="生成配置" :column="2" border>
              <el-descriptions-item label="数据源">{{ selectedDatasource?.name }}</el-descriptions-item>
              <el-descriptions-item label="表名">{{ selectedTable }}</el-descriptions-item>
              <el-descriptions-item label="生成记录数">{{ form.record_count }}</el-descriptions-item>
              <el-descriptions-item label="生成字段数">{{ generateFields.length }}</el-descriptions-item>
              <el-descriptions-item label="清空现有数据">{{ form.truncate_table ? '是' : '否' }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div class="generation-actions">
            <el-button type="success" size="large" @click="generateData" :loading="generating">
              ⚡ {{ generating ? '生成中...' : '开始生成' }}
            </el-button>
            <el-button size="large" @click="previewData" :loading="previewing">
              👁️ {{ previewing ? '预览中...' : '预览数据' }}
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 生成结果 -->
      <el-card shadow="hover" class="result-card" v-if="generateResult.success">
        <template #header>
          <div class="card-header">
            <span>生成结果</span>
            <div>
              <el-button type="success" @click="downloadCsv">
                📥 下载CSV
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="result-info">
          <el-alert
            title="数据生成成功"
            type="success"
            :closable="false"
            show-icon
          >
            <div class="result-summary">
              <div>表名：{{ generateResult.table_name }}</div>
              <div>记录数：{{ generateResult.record_count }}</div>
              <div>字段数：{{ generateResult.field_count }}</div>
              <div>数据源：{{ generateResult.datasource_name }}</div>
            </div>
          </el-alert>
        </div>
        
        <!-- 数据预览 -->
        <div class="data-preview">
          <div class="preview-title">数据预览</div>
          <el-table
            :data="generateResult.preview_data"
            border
            style="width: 100%"
            max-height="400"
          >
            <el-table-column
              v-for="field in generateFields"
              :key="field.name"
              :prop="field.name"
              :label="field.name"
              min-width="120"
            />
          </el-table>
        </div>
      </el-card>

      <!-- 预览结果 -->
      <el-card shadow="hover" class="preview-card" v-if="previewResult.length > 0">
        <template #header>
          <div class="card-header">
            <span>数据预览</span>
            <el-button type="text" @click="closePreview">关闭预览</el-button>
          </div>
        </template>
        
        <el-table
          :data="previewResult"
          border
          style="width: 100%"
          max-height="400"
        >
          <el-table-column
            v-for="field in generateFields"
            :key="field.name"
            :prop="field.name"
            :label="field.name"
            min-width="120"
          />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 暂时不使用图标，避免导入问题
import { getDatasourceList, getDatabaseTables } from '@/api/datasource'
import { generateFakeData, getTableSchema, previewFakeData } from '@/api/fake-data'

// 当前步骤
const currentStep = ref(0)

// 数据源相关
const datasourceOptions = ref([])
const selectedDatasource = ref(null)

// 表相关
const tableOptions = ref([])
const selectedTable = ref('')
const tableSearchKeyword = ref('')
const loadingTables = ref(false)

// 字段相关
const tableFields = ref([])
const loadingSchema = ref(false)

// 表单数据
const form = reactive({
  record_count: 1000,
  truncate_table: false
})

// 生成相关
const generating = ref(false)
const previewing = ref(false)

// 生成结果
const generateResult = ref({
  success: false,
  table_name: '',
  record_count: 0,
  field_count: 0,
  datasource_name: '',
  preview_data: []
})

// 预览结果
const previewResult = ref([])

// 计算属性
const filteredTables = computed(() => {
  if (!tableSearchKeyword.value) {
    return tableOptions.value
  }
  return tableOptions.value.filter(table => 
    table.toLowerCase().includes(tableSearchKeyword.value.toLowerCase())
  )
})

const generateFields = computed(() => {
  return tableFields.value.filter(field => field.generate && !field.auto_increment)
})

// 获取数据源列表
const getDatasources = async () => {
  try {
    const res = await getDatasourceList()
    if (res.code === 200) {
      datasourceOptions.value = res.data.filter(item => item.status === 'connected')
    } else {
      ElMessage.error('获取数据源列表失败')
    }
  } catch (error) {
    console.error('获取数据源列表失败:', error)
    ElMessage.error('获取数据源列表失败')
  }
}

// 选择数据源
const selectDatasource = (datasource) => {
  selectedDatasource.value = datasource
}

// 加载表列表
const loadTables = async () => {
  if (!selectedDatasource.value) return
  
  loadingTables.value = true
  try {
    const res = await getDatabaseTables(selectedDatasource.value.id)
    if (res.code === 200) {
      tableOptions.value = res.data || []
    } else {
      ElMessage.error('获取表列表失败')
    }
  } catch (error) {
    console.error('获取表列表失败:', error)
    ElMessage.error('获取表列表失败')
  } finally {
    loadingTables.value = false
  }
}

// 选择表
const selectTable = (table) => {
  selectedTable.value = table
}

// 加载表结构
const loadTableSchema = async () => {
  if (!selectedDatasource.value || !selectedTable.value) return
  
  loadingSchema.value = true
  try {
    const res = await getTableSchema(selectedDatasource.value.id, selectedTable.value)
    if (res.code === 200) {
      tableFields.value = res.data.fields || []
    } else {
      ElMessage.error('获取表结构失败')
    }
  } catch (error) {
    console.error('获取表结构失败:', error)
    ElMessage.error('获取表结构失败')
  } finally {
    loadingSchema.value = false
  }
}

// 步骤控制
const nextStep = async () => {
  if (currentStep.value === 1) {
    // 从步骤2到步骤3时，加载表结构
    await loadTableSchema()
  }
  currentStep.value++
}

const prevStep = () => {
  currentStep.value--
}

// 字段配置相关
const updateFieldGenerate = (index) => {
  // 字段生成状态更新
}

const handleFieldTypeChange = (index) => {
  const field = tableFields.value[index]
  
  // 根据字段类型设置默认值
  switch (field.type) {
    case 'integer':
      field.min = field.min || 1
      field.max = field.max || 1000
      break
    case 'float':
      field.min = field.min || 0.0
      field.max = field.max || 1000.0
      field.precision = field.precision || 2
      break
    case 'string':
    case 'text':
      field.min_length = field.min_length || 1
      field.max_length = field.max_length || 20
      break
    case 'datetime':
      field.start_date = field.start_date || '2023-01-01 00:00:00'
      field.end_date = field.end_date || '2024-12-31 23:59:59'
      break
    case 'date':
      field.start_date = field.start_date || '2023-01-01'
      field.end_date = field.end_date || '2024-12-31'
      break
    case 'enum':
      field.values = field.values || 'option1,option2,option3'
      break
  }
}

const autoConfigAllFields = () => {
  // 智能配置所有字段
  tableFields.value.forEach((field, index) => {
    if (!field.auto_increment) {
      field.generate = true
      handleFieldTypeChange(index)
    }
  })
  ElMessage.success('智能配置完成')
}

const toggleAllFields = () => {
  const allSelected = tableFields.value.every(field => field.generate || field.auto_increment)
  tableFields.value.forEach(field => {
    if (!field.auto_increment) {
      field.generate = !allSelected
    }
  })
}

// 数据生成
const generateData = async () => {
  if (generateFields.value.length === 0) {
    ElMessage.warning('请至少选择一个字段进行生成')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要生成 ${form.record_count} 条数据到表 "${selectedTable.value}" 吗？${form.truncate_table ? '（将清空现有数据）' : ''}`,
      '确认生成',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    generating.value = true
    
    const requestData = {
      datasource_id: selectedDatasource.value.id,
      table_name: selectedTable.value,
      record_count: form.record_count,
      truncate_table: form.truncate_table,
      fields: generateFields.value
    }
    
    const res = await generateFakeData(requestData)
    if (res.code === 200) {
      generateResult.value = res.data
      generateResult.value.success = true
      ElMessage.success('数据生成成功')
    } else {
      ElMessage.error(res.message || '数据生成失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('生成数据失败:', error)
      if (error.response?.data?.message) {
        ElMessage.error(error.response.data.message)
      } else {
        ElMessage.error('数据生成失败')
      }
    }
  } finally {
    generating.value = false
  }
}

// 预览数据
const previewData = async () => {
  if (generateFields.value.length === 0) {
    ElMessage.warning('请至少选择一个字段进行预览')
    return
  }
  
  previewing.value = true
  try {
    const requestData = {
      fields: generateFields.value,
      record_count: 10
    }
    
    const res = await previewFakeData(requestData)
    if (res.code === 200) {
      previewResult.value = res.data
      ElMessage.success('预览数据生成成功')
    } else {
      ElMessage.error(res.message || '预览数据失败')
    }
  } catch (error) {
    console.error('预览数据失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('预览数据失败')
    }
  } finally {
    previewing.value = false
  }
}

// 关闭预览
const closePreview = () => {
  previewResult.value = []
}

// 下载CSV
const downloadCsv = () => {
  const fields = generateFields.value.map(field => field.name)
  const data = generateResult.value.preview_data
  
  // 生成CSV内容
  let csvContent = fields.join(',') + '\n'
  
  data.forEach(row => {
    const rowValues = fields.map(field => {
      const value = row[field]
      
      // 处理包含逗号的字符串
      if (typeof value === 'string' && value.includes(',')) {
        return `"${value}"`
      }
      
      return value
    })
    
    csvContent += rowValues.join(',') + '\n'
  })
  
  downloadFile(`${selectedTable.value}.csv`, csvContent)
}

// 下载文件
const downloadFile = (filename, content) => {
  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  link.click()
  
  URL.revokeObjectURL(url)
}

// 监听数据源变化
watch(selectedDatasource, (newDatasource) => {
  if (newDatasource) {
    loadTables()
  }
})

onMounted(() => {
  getDatasources()
})
</script>

<style lang="scss" scoped>
.page-container {
  padding: 20px;
}

.steps-container {
  margin-bottom: 30px;
}

.step-card {
  margin-bottom: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.datasource-selection {
  .datasource-item {
    margin-bottom: 20px;
    
    .datasource-card {
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
      
      &.selected {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }
    
    .datasource-info {
      display: flex;
      align-items: center;
      
      .datasource-icon {
        font-size: 32px;
        margin-right: 15px;
      }
      
      .datasource-details {
        flex: 1;
        
        .datasource-name {
          font-size: 16px;
          font-weight: bold;
          margin-bottom: 5px;
        }
        
        .datasource-type {
          color: #409eff;
          font-size: 12px;
          margin-bottom: 3px;
        }
        
        .datasource-host {
          color: #909399;
          font-size: 12px;
          margin-bottom: 5px;
        }
      }
    }
  }
}

.table-selection {
  .selected-datasource-info {
    margin-bottom: 20px;
  }
  
  .table-search {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
  }
  
  .table-list {
    .table-item {
      margin-bottom: 15px;
      
      .table-card {
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        &.selected {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }
      
      .table-info {
        text-align: center;
        
        .table-icon {
          font-size: 24px;
          margin-bottom: 10px;
        }
        
        .table-name {
          font-weight: bold;
        }
      }
    }
  }
}

.field-configuration {
  .selected-info {
    margin-bottom: 20px;
  }
  
  .config-form {
    margin-bottom: 20px;
    
    .form-tip {
      margin-left: 10px;
      color: #909399;
      font-size: 12px;
    }
  }
  
  .fields-config {
    .fields-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h3 {
        margin: 0;
      }
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .fields-list {
      .field-item {
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 15px;
        
        .field-header {
          margin-bottom: 10px;
          
          .field-name {
            font-weight: bold;
            margin-right: 10px;
          }
          
          .field-type-tag {
            margin-right: 5px;
          }
        }
        
        .field-config {
          padding-left: 24px;
          
          .config-row {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            
            .config-label {
              min-width: 80px;
              margin-right: 10px;
              font-size: 14px;
            }
            
            .range-separator {
              margin: 0 10px;
              color: #909399;
            }
          }
        }
      }
    }
  }
}

.data-generation {
  .generation-summary {
    margin-bottom: 30px;
  }
  
  .generation-actions {
    text-align: center;
    
    .el-button {
      margin: 0 10px;
    }
  }
}

.step-actions {
  text-align: center;
  margin-top: 30px;
  
  .el-button {
    margin: 0 10px;
  }
}

.result-card, .preview-card {
  margin-top: 20px;
  
  .result-info {
    margin-bottom: 20px;
    
    .result-summary {
      margin-top: 10px;
      display: flex;
      gap: 20px;
    }
  }
  
  .data-preview {
    margin-top: 20px;
    
    .preview-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
    }
  }
}
</style>